#!/usr/bin/python
"""
    ICMime - IceCoder's mimetype manager.
    Copyright (C) 2011 Alfredo 'IceCoder' Mungo

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import os;
import sys;

tempdir = "/tmp"
appdir = "/usr/share/applications"

def mimeHelp():
  print("IceCoder's mimetype manager")
  print("Usage: ic_mime {command} [arguments]")
  print()
  print("Commands:")
  print("\tadd {mime type} {vendor} {description} {pattern1[ pattern2[ ...]]}: Adds the chosen mime type.\n")
  print("\tlist: Lists all the available applications that can be linked to mime types.\n")
  print("\tseticon {mime type} {icon path} {icon width}: Sets the icon for a mimetype\n")
  print("\tset {mime type} {application}: Sets the default application for the mimetype.\n")
  print()

def mimeList():
  global appdir
  os.system("ls " + appdir + " | sed s/\".desktop\"//")

def loadRC(): #Loads and parses the .icetoolsrc file to get the temp directory
  global tempdir
  path = os.environ['HOME'] + '/.icetoolsrc'
  if not os.path.exists(path):
    print("No config file detected, please run ic_setup first.")
    sys.exit(0)
    
  with open(path, 'r') as f:
    for line in f:
      line = line.strip()
      if not len(line) == 0: #not an empty line
        if not line.find('#') == 0: #not a comment
          lines = line.split('=', 2)
          name = lines[0].strip()
          content = lines[1].strip()
          if name == 'tempdir': #that's our variable!!
            tempdir = content
            return
  print("Unable to find the temp directory into the config file, please set your 'tempdir' variable!")
  sys.exit(0)

def checkDir(): #Checks if the tempdir is a directory and read/writable
  global tempdir
  if os.path.isdir(tempdir): #it's a directory
    if os.access(tempdir, os.R_OK | os.W_OK): #it's read/writable
      return
  print("Your selected temporary directory ('" + tempdir + "') does not exist, is not a directory or it is not read/writable.")
  print("Please check it or run ic_setup to change the temporary directory to yours.")
  sys.exit(0)

def mimeAdd(mime, vendor, desc, patterns):
  global tempdir
  if vendor == None:
    path = tempdir + '/' + mime.split('/')[-1] + ".xml"
  else:
    path = tempdir + '/' + vendor + '-' + mime.split('/')[-1] + ".xml"
  try:
    with open(path, 'w') as f:
      f.write('<?xml version="1.0"?>\n')
      f.write('<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">\n')
      f.write('<mime-type type="' + mime + '">\n')
      f.write('<comment>' + desc + '</comment>\n')
      for pat in patterns:
        f.write('<glob pattern="' + pat + '"/>\n')
      f.write('</mime-type>\n')
      f.write('</mime-info>\n')
  except IOError:
    print("Error while working on temporary file.")
  
  if vendor == None:
    os.system('xdg-mime install --novendor ' + path)
  else:
    os.system('xdg-mime install ' + path)

def mimeSetIcon(mime, icon, sz):
  mime = mime.replace('/', '-')
  os.system('xdg-icon-resource install --context mimetypes --size ' + sz + ' ' + icon)

def mimeSet(mime, app):
  global appdir
  appf = appdir + "/" + app + ".desktop"
  if os.path.exists(appf):
    os.system("xdg-mime default \"" + appf + "\" " + mime)
  else:
    print("The selected application does not exist or is not available for mimetypes linkage.")
    print("Please launch 'ic_mime list' to see the complete list of available applications.")
    sys.exit(0)
  
loadRC()
checkDir()

if len(sys.argv) == 1:
  mimeHelp()
else:
  cmd = sys.argv[1]
  if cmd == "list":
    mimeList()
  elif cmd == "add":
    if len(sys.argv) >= 6: #right amount of args
      patterns = sys.argv[5:]
      if not sys.argv[3] == "none":
        mimeAdd(sys.argv[2], sys.argv[3], sys.argv[4], patterns)
      else:
        mimeAdd(sys.argv[2], None, sys.argv[4], patterns)
    else:
      mimeHelp()
  elif cmd == "seticon":
    if len(sys.argv) == 5: #right amount of args
      mimeSetIcon(sys.argv[2], sys.argv[3], sys.argv[4])
    else:
      mimeHelp()
  elif cmd == "set":
    if len(sys.argv) == 4: #right amount of args
      mimeSet(sys.argv[2], sys.argv[3])
    else:
      mimeHelp()
  else:
    mimeHelp()

